#include <nds.h>
#include <stdio.h>

#include "bmpformat.h"

// graphics files
#include "Sonic001_bin.h"
#include "Sonic002_bin.h"
#include "Sonic003_bin.h"
#include "Sonic004_bin.h"
#include "Sonic005_bin.h"
#include "Sonic006_bin.h"
#include "Sonic007_bin.h"
#include "Sonic008_bin.h"

//---------------------------------------------------------------------------------
int setupVideoBackground(void)
{
        //set video mode to mode 5
        videoSetMode(MODE_5_2D);        
        //map vram a to slot 0 of background graphics memory
        vramSetBankA(VRAM_A_MAIN_BG_0x06000000);
        //map vram b to slot 1 of background graphics memory
        vramSetBankB(VRAM_B_MAIN_BG_0x06020000);
        //initialize the background layer
        return bgInit(3, BgType_Bmp8, BgSize_B8_256x256, 0,0);
}

//---------------------------------------------------------------------------------
int main(void) {
//---------------------------------------------------------------------------------
	
	int frame = 0;
	int bg;
	unsigned char delay;
	unsigned char swapped = 0;
	const unsigned int base_a = 0;
	const unsigned int base_b = 8; // 128k screen / 16k chunk sizes
	u16 *back_buffer;
	BmpFile *bmp[8] =
	{
		(BmpFile *)Sonic001_bin,
		(BmpFile *)Sonic002_bin,
		(BmpFile *)Sonic003_bin,
		(BmpFile *)Sonic004_bin,
		(BmpFile *)Sonic005_bin,
		(BmpFile *)Sonic006_bin,
		(BmpFile *)Sonic007_bin,
		(BmpFile *)Sonic008_bin
	};


	consoleDemoInit();
	bg = setupVideoBackground();

	for (frame = 0 ; frame < 8 ; frame++)
	{
		//print_BmpInfo(bmp[frame]);
		validateBmp(bmp[frame]);
	}

	frame = 0;
	swapped = 0;
	while(1) 
	{
		if (swapped == 0)
		{
			swapped = 1;
			bgSetMapBase(bg, base_a);
			back_buffer = BG_BMP_RAM(base_b);
		}
		else
		{
			swapped = 0;
			bgSetMapBase(bg, base_b);
			back_buffer = BG_BMP_RAM(base_a);
		}

		displayIndexedBmp(bmp[frame], back_buffer);

		for(delay = 0 ; delay < 4 ; delay++)
		{
		 	swiWaitForVBlank(); // extra to slow Sonic down
		}

		uploadPalette(bmp[frame], BG_PALETTE);

		if  (++frame > 7) frame = 0;
 	}

	return 0;
}
